<?php

namespace app\common\model\xilumarket;

use app\common\library\Auth;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use function fast\array_get;

class FooterView extends Model
{
    protected $name = 'xilumarket_footer_view';
    protected $autoWriteTimestamp = 'int';


    protected $createTime = 'createtime';
    protected $updateTime = false;

    const TYPE_FORUM = 1; //论坛
    const TYPE_PRODUCT = 2; //闲置
    const TYPE_RECOVERY = 3; //回收

    /**
     * 浏览记录
     * @param int $userId
     * @param int $footer_id
     * @return
     */
    public static function viewFooter($userId, $footer_id,$type) {
        if(!$userId || !$footer_id || !$type) {
            throw new Exception(__('invalid arguments'));
        }
        Db::startTrans();
        try {
            $record = static::where('user_id',$userId)->where('footer_id', $footer_id)->where('type',$type)->find();
            $now = time();
            if(!$record) {
                $record = new static();
                $record->save(['type'=>$type,'user_id'=>$userId,'footer_id'=>$footer_id,'view_time'=>$now]);
            }else {
                //两小时内不重复加
                $data = ['view_time'=>time()];
                if($now>$record->view_time+3600*2) {
                    $data['view_count'] = Db::raw('view_count+1');
                }
                $record->save($data);
            }
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Db::rollback();
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            throw $e;
        }
    }

    public function forum(){
        return $this->belongsTo(TopicForum::class,'footer_id','id',[],'INNER')->setEagerlyType(0);
    }

    public function product(){
        return $this->belongsTo(Product::class,'footer_id','id',[],'INNER')->setEagerlyType(0);
    }

    /**
     * 根据条件数量
     */
    public static function getCount($where){
        return self::where($where)->count();
    }

    /**
     * 我的足迹
     */
    public static function lists($parmas,$user_id){
        $pagesize = array_get($parmas,'pagesize',10);
        $where['user_id'] = $user_id;
        $where['type'] = self::TYPE_PRODUCT;
        return static::field("footer_id,type,view_time")
            ->where($where)
            ->order('view_time','desc')
            ->paginate($pagesize)
            ->each(function ($row){
                if($row['type'] == self::TYPE_FORUM){
                    $row->relationQuery(['forum']);
                }else if($row['type'] == self::TYPE_PRODUCT){
                    $row->relationQuery(['product'=>function($q){
                        $q->field(['id','thumb_image','name','salesprice']);
                    }]);
                }else if($row['type'] == self::TYPE_RECOVERY){
                    $row->recovery;
                }
            });
    }

}
